<template>
  <div class="note-detail">
    <el-card>
      <img v-if="note.image" :src="`http://localhost:8000/storage/${note.image}`" alt="笔记图片" />
      <h2>{{ note.title }}</h2>
      <p>{{ note.content }}</p>
      <p>作者: {{ note.user?.username || '未知' }}</p>
      <el-button type="primary" @click="toggleLike">
        {{ isLiked ? '取消点赞' : '点赞' }} ({{ note.likes?.length || 0 }})
      </el-button>
      <el-form @submit.prevent="submitComment" style="margin-top: 20px;">
        <el-input v-model="commentContent" type="textarea" placeholder="写下你的评论" rows="3" />
        <el-button type="primary" native-type="submit" style="margin-top: 10px;">发表评论</el-button>
      </el-form>
      <div class="comments" v-if="note.comments?.length">
        <el-card v-for="comment in note.comments" :key="comment.id" style="margin-top: 10px;">
          <p>{{ comment.content }}</p>
          <p>评论者: {{ comment.user?.username || '未知' }}</p>
        </el-card>
      </div>
      <el-button type="primary" @click="$router.push('/explore')">返回</el-button>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { useAuthStore } from '../stores/auth';

const route = useRoute();
const router = useRouter();
const authStore = useAuthStore();
const note = ref({});
const commentContent = ref('');
const isLiked = ref(false);

const fetchNote = async () => {
  try {
    const response = await axios.get(`/api/notes/${route.params.id}`);
    note.value = response.data;
    isLiked.value = note.value.likes?.some(like => like.user_id === authStore.user?.id);
  } catch (error) {
    console.error('获取笔记详情失败:', error);
  }
};

onMounted(fetchNote);

const toggleLike = async () => {
  if (!authStore.token) {
    return router.push(`/login?redirect=/notes/${route.params.id}`);
  }
  try {
    const response = await axios.post(`/api/notes/${route.params.id}/likes`, {}, {
      headers: { Authorization: `Bearer ${authStore.token}` },
    });
    isLiked.value = response.data.liked;
    fetchNote(); // 刷新点赞数
  } catch (error) {
    alert('点赞失败：' + (error.response?.data?.message || '未知错误'));
  }
};

const submitComment = async () => {
  if (!authStore.token) {
    return router.push(`/login?redirect=/notes/${route.params.id}`);
  }
  try {
    await axios.post(`/api/notes/${route.params.id}/comments`, { content: commentContent.value }, {
      headers: { Authorization: `Bearer ${authStore.token}` },
    });
    commentContent.value = '';
    fetchNote(); // 刷新评论
  } catch (error) {
    alert('评论失败：' + (error.response?.data?.message || '未知错误'));
  }
};
</script>

<style scoped>
.note-detail { max-width: 800px; margin: 20px auto; padding: 20px; }
img { width: 100%; max-height: 300px; object-fit: cover; }
</style>